package com.habdqn.easybuy.web.manage.user;

import com.habdqn.easybuy.entity.User;
import com.habdqn.easybuy.service.UserService;
import com.habdqn.easybuy.service.impl.UserServiceImpl;
import com.habdqn.easybuy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Xing.Jiejian
 * @date 2020/11/26 0026
 */
@WebServlet(name = "UserAddServlet", urlPatterns = "/manage/user/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        user.setSex(request.getParameter("sex"));
        String strBirthday = request.getParameter("birthday");
        if (StringUtils.isNotBlank(strBirthday)) {
            try {
                Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse(strBirthday);
                user.setBirthday(birthday);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        user.setEmail(request.getParameter("email"));
        user.setMobile(request.getParameter("mobile"));
        user.setAddress(request.getParameter("address"));

        UserService userService = new UserServiceImpl();
        if (userService.insert(user).getId() != null) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<script>");
            out.println("alert('新增用户成功！');");
            out.println("location.href='" + request.getContextPath() + "/manage/user';");
            out.println("</script>");
        } else {
            request.setAttribute("errorMsg", "新增失败");
            doGet(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/manage/user/user-add.jsp").forward(request, response);
    }
}
